package com.zh.auth.config;

import cn.hutool.core.util.StrUtil;
import com.zh.auth.properties.RsaProperties;
import com.zh.common.exception.BusinessException;
import com.zh.common.utils.RSAUtil;
import com.zh.common.utils.RedisUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

/**
 * 初始化配置
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class StartupConfig {

    private final RsaProperties rsaProperties;
    private final RedisUtil redisUtil;

    @PostConstruct
    public void init() {
        initRsa();
    }

    /**
     * 初始化公钥和私钥
     */
    private void initRsa() {
        try {
            String privateKey = rsaProperties.getPrivateKey();
            String publicKey = rsaProperties.getPublicKey();
            String privateKeyString = redisUtil.get(privateKey);
            String publicKeyKeyString = redisUtil.get(publicKey);
            switch (rsaProperties.getMode()) {
                case STRICT:
                    redisUtil.delete(rsaProperties.getPrivateKey());
                    redisUtil.delete(rsaProperties.getPublicKey());
                    RSAUtil.keyPairMap = RSAUtil.generateKey();
                    break;
                case TEMPORARY:
                    if (StrUtil.isNotEmpty(privateKeyString) && StrUtil.isNotEmpty(publicKeyKeyString)) {
                        RSAUtil.keyPairMap.put(RSAUtil.privateKeyName, privateKeyString);
                        RSAUtil.keyPairMap.put(RSAUtil.publicKeyName, publicKeyKeyString);
                    } else {
                        RSAUtil.generateKey();
                        redisUtil.set(privateKey, RSAUtil.getPrivateKey(), 1, TimeUnit.DAYS);
                        redisUtil.set(privateKey, RSAUtil.getPublicKey(), 1, TimeUnit.DAYS);
                    }
                    break;
                case PERMANENT:
                    if (StrUtil.isNotEmpty(privateKeyString) && StrUtil.isNotEmpty(publicKeyKeyString)) {
                        RSAUtil.keyPairMap.put(RSAUtil.privateKeyName, privateKeyString);
                        RSAUtil.keyPairMap.put(RSAUtil.publicKeyName, publicKeyKeyString);
                    } else {
                        RSAUtil.generateKey();
                        redisUtil.set(privateKey, RSAUtil.getPrivateKey(), 365, TimeUnit.DAYS);
                        redisUtil.set(publicKey, RSAUtil.getPublicKey(), 365, TimeUnit.DAYS);
                    }
                    break;
                default:
                    throw new RuntimeException("RSA mode is not supported");
            }
            log.info("==========初始化公钥和私钥成功==========");
        } catch (Exception e) {
            throw new BusinessException("初始化公钥和私钥失败");
        }
    }
}
